package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        // 创建队列 helloworld
        c.queueDeclare("task_queue", true, false, false, null);

        // 回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到： "+s);
                // 模拟阻塞的消息
                // 遍历字符串找 '.'，每找到一个都暂停一秒
                for (int i = 0; i < s.length(); i++) {
                    if ('.' == s.charAt(i)) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                // 发送回执
                // c.basicAck(回执, 是否把之前收过的多条消息一起进行确认);
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("----------------消息处理结束\n");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        // 每次只接收一条消息，处理完之前不接收下一条
        c.basicQos(1);

        // 接收消息
        c.basicConsume("task_queue",false, deliverCallback, cancelCallback);
    }
}
